extends Node
class_name SaveSystem

const SAVE_PATH := "user://save.json"

signal game_loaded(data: Dictionary)
signal game_saved()

func save_game(state: Dictionary) -> void:
	var file := FileAccess.open(SAVE_PATH, FileAccess.WRITE)
	if file == null:
		print("Error: Could not open save file for writing")
		return
	
	file.store_string(JSON.stringify(state))
	file.close()
	game_saved.emit()
	print("Game saved successfully")

func load_game() -> Dictionary:
	if not FileAccess.file_exists(SAVE_PATH):
		print("No save file found, creating new game")
		return create_new_game_data()
	
	var file := FileAccess.open(SAVE_PATH, FileAccess.READ)
	if file == null:
		print("Error: Could not open save file for reading")
		return create_new_game_data()
	
	var text := file.get_as_text()
	file.close()
	
	var json := JSON.new()
	var parse_result := json.parse(text)
	
	if parse_result != OK:
		print("Error parsing save file, creating new game")
		return create_new_game_data()
	
	var result = json.data
	if typeof(result) != TYPE_DICTIONARY:
		print("Invalid save data format, creating new game")
		return create_new_game_data()
	
	game_loaded.emit(result)
	print("Game loaded successfully")
	return result

func create_new_game_data() -> Dictionary:
	var field_data := []
	for y in range(15):
		var row := []
		for x in range(20):
			row.append({
				"plowed": false,
				"wet_until": 0,
				"crop_id": null,
				"stage": 0,
				"planted_time": 0,
				"last_water_time": 0
			})
		field_data.append(row)
	
	return {
		"time": {
			"day": 1,
			"hour": 8,
			"speed": 1
		},
		"money": 100,
		"stamina": 100,
		"max_stamina": 100,
		"field": {
			"width": 20,
			"height": 15,
			"tiles": field_data
		},
		"inventory": [
			{"id": "seed_turnip", "count": 5},
			{"id": "seed_potato", "count": 3},
			{"id": "seed_corn", "count": 2}
		],
		"options": {
			"volume_bgm": 0.8,
			"volume_sfx": 0.8
		}
	}

func has_save_file() -> bool:
	return FileAccess.file_exists(SAVE_PATH)